<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="utf-8">
    <meta name="viewport"
          content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no"/>
    <title>书籍信息管理</title>
    <link rel="icon"
          href="${pageContext.request.contextPath }/static/plugins/lightyear/favicon.ico"
          type="image/ico">
    <meta name="keywords" content="书籍信息管理">
    <meta name="description" content="书籍信息管理">
    <link href="${pageContext.request.contextPath }/static/css/common.css"
          rel="stylesheet">
    <link
            href="${pageContext.request.contextPath }/static/plugins/lightyear/css/bootstrap.min.css"
            rel="stylesheet">
    <link
            href="${pageContext.request.contextPath }/static/plugins/lightyear/css/materialdesignicons.min.css"
            rel="stylesheet">
    <link
            href="${pageContext.request.contextPath }/static/plugins/lightyear/css/animate.css"
            rel="stylesheet">
    <link
            href="${pageContext.request.contextPath }/static/plugins/lightyear/css/style.min.css"
            rel="stylesheet">
    <link
            href="${pageContext.request.contextPath }/static/plugins/lightyear/js/bootstrap-table/bootstrap-table.min.css"
            rel="stylesheet">
</head>

<body>
<div class="container-fluid p-t-15">

    <div class="row">
        <div class="col-lg-12">
            <div class="card">
                <div class="card-header">
                    <h4>图书管理</h4>
                </div>
                <div class="card-body">

                    <div id="toolbar" class="toolbar-btn-action">
                        <button id="btn_add" type="button" class="btn btn-primary m-r-5">
                            <span class="mdi mdi-plus" aria-hidden="true"></span>新增
                        </button>
                        <button id="btn_delete" type="button" class="btn btn-danger">
                            <span class="mdi mdi-window-close" aria-hidden="true"></span>删除
                        </button>
                        <button id="btn_restart" type="button" class="btn btn-info">
                            <span class="mdi mdi-restart" aria-hidden="true"></span> <a
                                href="javascript:location.reload();"
                                style="text-decoration: none; color: white;">刷新</a>
                        </button>
                    </div>
                    <table id="tb_departments"></table>
                </div>
            </div>
        </div>
    </div>
</div>

<!--新增操作model-->
<div class="modal fade" id="addModel" tabindex="-1" role="dialog"
     aria-labelledby="myModalLabel" style="border-radius: 5px;">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal"
                        aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
                <h4 class="modal-title" id="updateLabel">新增书籍</h4>
            </div>
            <div class="modal-body">
                <form id="addForm" action="" method="POST">
                    <div class="row">
                        <div class="col-sm-6">
                            <div class="input-group">
									<span class="input-group-addon"><i
                                            class="mdi mdi-rename-box"></i>名称</span> <input id="addName"
                                                                                            type="text" name="name"
                                                                                            class="form-control"
                                                                                            placeholder="例如：JAVA从入门到入坟"
                                                                                            maxlength="50">
                            </div>
                        </div>
                        <div class="col-sm-6">
                            <div class="input-group">
									<span class="input-group-addon"><i
                                            class="mdi mdi-account-circle"></i>作者</span> <input id="addAuthor"
                                                                                                type="text"
                                                                                                name="author"
                                                                                                class="form-control"
                                                                                                placeholder="例如：小明"
                                                                                                maxlength="30">
                            </div>
                        </div>
                        <div class="col-sm-6">
                            <div class="input-group">
                                <span class="input-group-addon">出版社</span> <input
                                    id="addPublish" type="text" name="publish"
                                    class="form-control" placeholder="例如：嘿嘿出版社" maxlength="50">
                            </div>
                        </div>
                        <div class="col-sm-6">
                            <div class="input-group">
                                <span class="input-group-addon">出版时间</span> <input
                                    id="addPublishTime" type="date" name="publishTime"
                                    class="form-control">
                            </div>
                        </div>
                        <div class="col-sm-12">
                            <div class="input-group">
                                <span class="input-group-addon">简介</span>
                                <textarea id="addIntroduction" name="introduction"
                                          class="form-control"
                                          style="text-align: left; resize: none;">这个人很懒，啥都没留下...</textarea>
                            </div>
                        </div>
                        <div class="col-sm-6">
                            <div class="input-group">
                                <span class="input-group-addon">分类</span> <select
                                    id="addTypeId" name="typeId" class="form-control">
                                <option value="0">分类加载...</option>
                            </select>
                            </div>
                        </div>
                        <div class="col-sm-6">
                            <div class="input-group">
                                <span class="input-group-addon">库存</span> <input type="text"
                                                                                 id="addCount" name="count"
                                                                                 class="form-control" maxlength="3">
                            </div>
                        </div>
                        <div class="col-sm-12 row">
                            <div class="col-sm-6">
                                <div class="input-group">
                                    <span class="input-group-addon">价格</span> <input type="text"
                                                                                     id="addPrice" name="price"
                                                                                     class="form-control" maxlength="10">
                                </div>
                            </div>
                        </div>
                        <div class="col-sm-6">
                            <div class="form-group">
                                <label for="addUpload">封面设置</label>
                                <input type="file" id="addUpload" name="upload">
                                <p class="help-block">请上传10M以内的jpg、png、gif图片。</p>
                            </div>
                        </div>
                        <div class="col-sm-6">
                            <img src="../../upload/face/0.png" id="addFace" alt="封面" width="100px">
                        </div>
                    </div>
                    <div class="modal-footer" class="form-control">
                        <button type="button" id="modal_add_btn" class="btn btn-success">提交</button>
                        <button type="button" class="btn btn-warning" data-dismiss="modal">取消</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<!-- 编辑书籍model -->
<div class="modal fade" id="updateModal" tabindex="-1" role="dialog"
     aria-labelledby="myModalLabel" style="border-radius: 5px;">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal"
                        aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
                <h4 class="modal-title" id="">编辑书籍</h4>
            </div>
            <div class="modal-body">
                <form id="updateForm" action="" method="POST">
                    <input type="hidden" name="id" id="updateId"/>
                    <div class="row">
                        <div class="col-sm-6">
                            <div class="input-group">
									<span class="input-group-addon"><i
                                            class="mdi mdi-rename-box"></i>名称</span> <input id="updateName"
                                                                                            type="text" name="name"
                                                                                            class="form-control"
                                                                                            placeholder="例如：JAVA从入门到入坟"
                                                                                            maxlength="50">
                            </div>
                        </div>
                        <div class="col-sm-6">
                            <div class="input-group">
									<span class="input-group-addon"><i
                                            class="mdi mdi-account-circle"></i>作者</span> <input id="updateAuthor"
                                                                                                type="text"
                                                                                                name="author"
                                                                                                class="form-control"
                                                                                                placeholder="例如：小明"
                                                                                                maxlength="30">
                            </div>
                        </div>
                        <div class="col-sm-6">
                            <div class="input-group">
                                <span class="input-group-addon">出版社</span> <input
                                    id="updatePublish" type="text" name="publish"
                                    class="form-control" placeholder="例如：嘿嘿出版社" maxlength="50">
                            </div>
                        </div>
                        <div class="col-sm-6">
                            <div class="input-group">
                                <span class="input-group-addon">出版时间</span> <input
                                    id="updatePublishTime" type="date" name="publishTime"
                                    class="form-control">
                            </div>
                        </div>
                        <div class="col-sm-12">
                            <div class="input-group">
                                <span class="input-group-addon">简介</span>
                                <textarea id="updateIntroduction" name="introduction"
                                          class="form-control"
                                          style="text-align: left; resize: none;">这个人很懒，啥都没留下...</textarea>
                            </div>
                        </div>
                        <div class="col-sm-6">
                            <div class="input-group">
                                <span class="input-group-addon">分类</span> <select
                                    id="updateTypeId" name="typeId" class="form-control">
                                <option value="0">分类加载....</option>
                            </select>
                            </div>
                        </div>
                        <div class="col-sm-6">
                            <div class="input-group">
                                <span class="input-group-addon">库存</span> <input type="text"
                                                                                 id="updateCount" name="count"
                                                                                 class="form-control"
                                                                                 maxlength="3">
                            </div>
                        </div>
                        <div class="col-sm-12 row">
                            <div class="col-sm-6">
                                <div class="input-group">
                                    <span class="input-group-addon">价格</span> <input type="text"
                                                                                     id="updatePrice" name="price"
                                                                                     class="form-control"
                                                                                     maxlength="10">
                                </div>
                            </div>
                        </div>
                        <div class="col-sm-6">
                            <div class="form-group">
                                <label for="updateUpload">封面设置</label>
                                <input type="file" id="updateUpload" name="upload">
                                <p class="help-block">请上传10M以内的jpg、png、gif图片。</p>
                            </div>
                        </div>
                        <div class="col-sm-6">
                            <img src="../../upload/face/0.png" id="updateFace" alt="封面" width="100px">
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" id="modal_update_btn" class="btn btn-success">提交</button>
                <button type="button" class="btn btn-warning" data-dismiss="modal">取消</button>
            </div>
        </div>
    </div>
</div>


<script type="text/javascript"
        src="${pageContext.request.contextPath }/static/plugins/lightyear/js/jquery.min.js"></script>
<script type="text/javascript"
        src="${pageContext.request.contextPath }/static/plugins/layer/layer.js"></script>
<script type="text/javascript"
        src="${pageContext.request.contextPath }/static/js/common.js"></script>
<script type="text/javascript"
        src="${pageContext.request.contextPath }/static/plugins/lightyear/js/bootstrap.min.js"></script>
<script type="text/javascript"
        src="${pageContext.request.contextPath }/static/plugins/lightyear/js/perfect-scrollbar.min.js"></script>
<script type="text/javascript"
        src="${pageContext.request.contextPath }/static/plugins/lightyear/js/bootstrap-table/bootstrap-table.min.js"></script>
<script type="text/javascript"
        src="${pageContext.request.contextPath }/static/plugins/lightyear/js/bootstrap-table/bootstrap-table-zh-CN.min.js"></script>

<!--行内编辑插件-->
<link
        href="${pageContext.request.contextPath }/static/plugins/lightyear/js/x-editable/1.5.1/bootstrap3-editable/css/bootstrap-editable.min.css"
        rel="stylesheet">
<script type="text/javascript"
        src="${pageContext.request.contextPath }/static/plugins/lightyear/js/x-editable/1.5.1/bootstrap3-editable/js/bootstrap-editable.min.js"></script>
<script type="text/javascript"
        src="${pageContext.request.contextPath }/static/plugins/lightyear/js/bootstrap-table/extensions/editable/bootstrap-table-editable.min.js"></script>

<script type="text/javascript"
        src="${pageContext.request.contextPath }/static/plugins/lightyear/js/main.min.js"></script>
<script type="text/javascript">
    //加载分类列表
    getTypes();
    //初始化数据表格
    $('#tb_departments').bootstrapTable({
        classes: 'table table-bordered table-hover table-striped',
        url: '${pageContext.request.contextPath }/book/findAll',
        method: 'get',
        dataType: 'json', // 因为本示例中是跨域的调用,所以涉及到ajax都采用jsonp,
        uniqueId: 'id',
        idField: 'id', // 每行的唯一标识字段
        toolbar: '#toolbar', // 工具按钮容器
        clickToSelect: false, // 是否启用点击选中行
        showColumns: true, // 是否显示所有的列
        showRefresh: true, // 是否显示刷新按钮

        //showToggle: true,        // 是否显示详细视图和列表视图的切换按钮(clickToSelect同时设置为true时点击会报错)

        pagination: true, // 是否显示分页
        sortOrder: "asc", // 排序方式
        queryParams: function (params) {
            var temp = {
                pageSize: params.limit, // 每页数据量
                offset: params.offset, // sql语句起始索引
                page: (params.offset / params.limit) + 1,
                sort: params.sort, // 排序的列名
                sortOrder: params.order, // 排序方式'asc' 'desc'
                keyWord: params.search
            };
            return temp;
        }, // 传递参数
        sidePagination: "server", // 分页方式：client客户端分页，server服务端分页
        pageNumber: 1, // 初始化加载第一页，默认第一页
        pageSize: 5, // 每页的记录行数
        pageList: [5, 10, 25, 50], // 可供选择的每页的行数
        search: true, // 是否显示表格搜索，此搜索是客户端搜索

        //showExport: true,        // 是否显示导出按钮, 导出功能需要导出插件支持(tableexport.min.js)
        //exportDataType: "basic", // 导出数据类型, 'basic':当前页, 'all':所有数据, 'selected':选中的数据

        columns: [{
            checkbox: true
            // 是否显示复选框
        }, {
            field: 'id',
            title: 'ID',
            sortable: true
            // 是否排序
        }, {
            field: 'name',
            title: '书名',
            sortable: true
        }, {
            field: 'price',
            title: '价格',
            sortable: true
        }, {
            field: 'author',
            title: '作者',
            sortable: true
        }, {
            field: 'publish',
            title: '出版社',
            sortable: true
        }, {
            field: 'publishTime',
            title: '出版时间',
            sortable: true
        }, {
            field: 'type.name',
            title: '分类',
        }, {
            field: 'count',
            title: '库存',
            sortable: true
        }, {
            field: 'createTimeStr',
            title: '创建时间',
        }, {
            field: 'operate',
            title: '操作',
            formatter: btnGroup, // 自定义方法
            events: {
                'click .edit-btn': function (event, value, row, index) {
                    editUser(row.id);
                },
                'click .del-btn': function (event, value, row, index) {
                    del(row.id);
                }
            }
        }],
        onLoadSuccess: function (data) {
            $("[data-toggle='tooltip']").tooltip();
        }
    });

    // 操作按钮
    function btnGroup() {
        let html = '<a href="#!" class="btn btn-xs btn-default m-r-5 edit-btn" title="编辑" data-toggle="tooltip" value="edit"><i class="mdi mdi-pencil"></i></a>'
            + '<a href="#!" class="btn btn-xs btn-default del-btn" title="删除" data-toggle="tooltip"><i class="mdi mdi-window-close"></i></a>';
        return html;
    }

    //回显编辑提交的封面
    $('#updateUpload').change(function (){
        // 获取用户最后一次选择的图片
        var choose_file=$(this)[0].files[0];
        // 创建一个新的FileReader对象，用来读取文件信息
        var reader=new FileReader();
        // 读取用户上传的图片的路径
        reader.readAsDataURL(choose_file);
        // 读取完毕之后，将图片的src属性修改成用户上传的图片的本地路径
        reader.onload=function () {
            $('#updateFace').attr("src",reader.result)
        }
    });

    // 操作方法 - 编辑
    function editUser(id) {
        //加载分类列表
        getTypes();
        //通过id查找用户信息，并渲染 编辑模态框
        $.get('${pageContext.request.contextPath}/book/findById', {
            id: id
        }, function (data) {
            //设置编辑模态框默认值
            $("#updateId").val(data.id);
            $("#updateName").val(data.name);
            $("#updateAuthor").val(data.author);
            $("#updatePublish").val(data.publish);
            $("#updatePublishTime").val(data.publishTime);
            $("#updateIntroduction").val(data.introduction);
            $("#updateTypeId").val(data.type.id);
            $("#updateCount").val(data.count);
            $("#updatePrice").val(data.price);
            $('#updateUpload').val(null);
            $('#updateFace').attr('src','${pageContext.request.contextPath}/upload/face/'+data.img);
            $("#updateModal").modal('show');
        });
    }

    // 操作方法 - 删除
    function del(id) {
        myLayer.confirm("确定删除这条记录？", function () {
            $.get('${pageContext.request.contextPath}/book/del', {
                id: id
            }, function (data) {
                if (data.flag) {
                    myLayer.successMsg(data.msg);
                    setTimeout(function () {
                        location.reload();
                    }, 1000);
                } else {
                    myLayer.errorMsg(data.msg);
                }
            });
        });
    }

    //提交修改后的信息
    $("#modal_update_btn").click(
        function () {
            var name = $.trim($("#updateName").val());
            var author = $.trim($("#updateAuthor").val());
            var publish = $.trim($("#updatePublish").val());
            var publishTime = $.trim($("#updatePublishTime").val());
            var introduction = $('#updateIntroduction').val();
            var typeId = $('#updateTypeId').val();
            var count = $.trim($("#updateCount").val());
            var price = $.trim($("#updatePrice").val());
            //输入验证：
            if (name == null || name.length == 0 || name == undefined) {
                myLayer.errorMsg("姓名必须填写！！");
                return false;
            }
            if (author == null || author.length == 0
                || author == undefined) {
                myLayer.errorMsg("作者必须填写！！");
                return false;
            }
            if (publish == null || publish.length == 0
                || publish == undefined) {
                myLayer.errorMsg("出版社必须填写！！");
                return false;
            }
            if (publishTime == null || publishTime.length == 0
                || publishTime == undefined) {
                myLayer.errorMsg("出版时间必须填写！！");
                return false;
            }
            if (count == null || count.length == 0
                || count == undefined) {
                $("#updateCount").val(0);
            }
            if (price == null || price.length == 0
                || price == undefined) {
                $("#updatePrice").val(0);
            }

            //组装上传表单内容
            var formData = new FormData();
            formData.append("id",$("#updateId").val());
            formData.append("upload",$('#updateUpload')[0].files[0]);
            formData.append("name",name );
            formData.append("author", author);
            formData.append("publish", publish);
            formData.append("publishTime", publishTime );
            formData.append("introduction", introduction );
            formData.append("typeId", typeId );
            formData.append("count", count );
            formData.append("price", price );

            //ajax上传表单
            $.ajax({
                url:'${pageContext.request.contextPath }/book/update',
                dataType:'json',
                type:'POST',
                data: formData,
                processData : false, // 使数据不做处理
                contentType : false, // 不要设置Content-Type请求头
                success: function(data){
                    if (data.flag) {
                        myLayer.successMsg(data.msg);
                        setTimeout(function () {
                            location.reload();
                        }, 1000);
                    } else {
                        myLayer.errorMsg(data.msg);
                    }
                },
                error:function(data){
                    myLayer.systemErrorMsg("系统错误，无法处理该请求！！请联系管理员");
                }
            });
        });

    //加载type列表
    function getTypes() {
        $.get(
            '${pageContext.request.contextPath }/type/findAllJson',
            function (data) {
                //获取原生选择标签，清空
                var addTypeSel = $("#addTypeId")[0];
                var updateTypeSel = $("#updateTypeId")[0];
                addTypeSel.length = 0;
                updateTypeSel.length = 0;
                $(data)
                    .each(
                        function () {
                            //添加元素
                            $(addTypeSel)
                                .append(
                                    $("<option value='" + this.id + "'>"
                                        + this.name
                                        + "</option>"));
                            $(updateTypeSel)
                                .append(
                                    $("<option value='" + this.id + "'>"
                                        + this.name
                                        + "</option>"));
                        });
            });
    }

    //批量删除
    $("#btn_delete").click(function () {
        var selects = $('#tb_departments').bootstrapTable('getSelections');
        if (selects.length == 0) {
            myLayer.errorMsg("请选择需要删除的记录！！");
            return false;
        }
        var ids = "";
        $(selects).each(function () {
            ids += this.id + ",";
        });
        ids = ids.substring(0, ids.length - 1);
        myLayer.confirm("确定删除选中的记录？", function () {
            $.get("${pageContext.request.contextPath}/book/delete", {
                ids: ids
            }, function (data) {

                if (data.flag) {
                    myLayer.successMsg(data.msg);
                    setTimeout(function () {
                        location.reload();
                    }, 1000);
                } else {
                    myLayer.errorMsg(data.msg);
                }
            });
        })
    });

    //回显提交的封面
    $('#addUpload').change(function (){
        // 获取用户最后一次选择的图片
        var choose_file=$(this)[0].files[0];
        // 创建一个新的FileReader对象，用来读取文件信息
        var reader=new FileReader();
        // 读取用户上传的图片的路径
        reader.readAsDataURL(choose_file);
        // 读取完毕之后，将图片的src属性修改成用户上传的图片的本地路径
        reader.onload=function () {
            $('#addFace').attr("src",reader.result)
        }
    });

    //点击增添按钮清空原表单数据
    $("#btn_add").click(function () {
        var name = $("#addName").val("");
        var author = $("#addAuthor").val("");
        var publish = $("#addPublish").val("");
        var publishTime = $("#addPublishTime").val(undefined);
        var introduction = $("#addIntroduction").val("这个人很懒，什么都没有留下");
        $('#addUpload').val(null);
        //获取类型数据列表
        getTypes();
        //显示数据
        $("#addModel").modal('show');
    });

    //提交增加数据
    $("#modal_add_btn").click(
        function () {
            var name = $.trim($("#addName").val());
            var author = $.trim($("#addAuthor").val());
            var publish = $.trim($("#addPublish").val());
            var publishTime = $.trim($("#addPublishTime").val());
            var introduction = $('#addIntroduction').val();
            var typeId = $('#addTypeId').val();
            var count = $.trim($("#addCount").val());
            var price = $.trim($("#addPrice").val());
            //输入验证：
            if (name == null || name.length == 0 || name == undefined) {
                myLayer.errorMsg("姓名必须填写！！");
                return false;
            }
            if (author == null || author.length == 0
                || author == undefined) {
                myLayer.errorMsg("作者必须填写！！");
                return false;
            }
            if (publish == null || publish.length == 0
                || publish == undefined) {
                myLayer.errorMsg("出版社必须填写！！");
                return false;
            }
            if (publishTime == null || publishTime.length == 0
                || publishTime == undefined) {
                myLayer.errorMsg("出版时间必须填写！！");
                return false;
            }
            if (count == null || count.length == 0
                || count == undefined) {
                $("#addCount").val(0);
            }
            if (price == null || price.length == 0
                || price == undefined) {
                $("#addPrice").val(0);
            }

            //组装上传表单内容
            var formData = new FormData();

            formData.append("upload",$('#addUpload')[0].files[0]);
            formData.append("name",name );
            formData.append("author", author);
            formData.append("publish", publish);
            formData.append("publishTime", publishTime );
            formData.append("introduction", introduction );
            formData.append("typeId", typeId );
            formData.append("count", count );
            formData.append("price", price );

            //ajax上传表单
            $.ajax({
                url:'${pageContext.request.contextPath }/book/add',
                dataType:'json',
                type:'POST',
                data: formData,
                processData : false, // 使数据不做处理
                contentType : false, // 不要设置Content-Type请求头
                success: function(data){
                    if (data.flag) {
                        myLayer.successMsg(data.msg);
                        setTimeout(function () {
                            location.reload();
                        }, 1000);
                    } else {
                        myLayer.errorMsg(data.msg);
                    }
                },
                error:function(data){
                    myLayer.systemErrorMsg("系统错误，无法处理该请求！！请联系管理员");
                }
            });
        });
</script>
</body>
</html>
